import React, { Component } from "react";
import { connect } from "dva";
import {
  Button,
  Input,
  Table,
  Divider,
  Popconfirm,
  Badge,
  Tooltip
} from "antd";
import styles from "./PushRules.less";
// import PushModal from './PushModal';
import PushRulesAdd from "./PushRulesAdd";

const { Search } = Input;

class PushRules extends Component {
  constructor(props) {
    super(props);
    this.state = {
      currentData: {},
      modalType: "add" // edit是修改弹出框
    };
  }

  columns = [
    {
      title: "序号",
      dataIndex: "ruleId",
      key: "ruleId",
      width: "70px",
      // TODO:切页的时候序号渲染太快
      render: (text, recode, index) => {
        const { filter } = this.props.pushRules;
        const currenPage = Number(filter.pageIndex);
        const PageSize = Number(filter.pageSize);
        const xuhao = Number(index) + 1 + (currenPage - 1) * PageSize;
        return xuhao;
      }
    },
    {
      title: "规则名称",
      dataIndex: "ruleName",
      key: "ruleName",
      width: "16%",
      render: text =>
        text && text.length > 15 ? (
          <Tooltip placement="top" title={text} arrowPointAtCenter>
            <span>{`${text.substring(0, 15)}……`}</span>
          </Tooltip>
        ) : (
          text
        )
    },
    {
      title: "规则应用",
      dataIndex: "appName",
      key: "appName",
      width: "10%"
    },
    {
      title: "规则描述",
      dataIndex: "comment",
      key: "comment",
      render: text =>
        text && text.length > 15 ? (
          <Tooltip placement="top" title={text} arrowPointAtCenter>
            <span>{`${text.substring(0, 15)}……`}</span>
          </Tooltip>
        ) : (
          text
        )
    },
    {
      title: "规则有效截止日期",
      dataIndex: "invalidTime",
      key: "invalidTime",
      render: text => (text ? text.substring(0, 11) : "不限"),
      sorter: true,
      width: "180px"
    },
    {
      title: "创建人",
      dataIndex: "creatorName",
      key: "creatorName",
      width: "10%"
    },
    {
      title: "状态",
      dataIndex: "statusDesc",
      key: "statusDesc",
      width: "90px",
      render: text => {
        let val = "";
        let code = text;
        if (code === "已启用") {
          val = "已启用";
          code = "success";
        } else {
          val = "已停用";
          code = "error";
        }
        return <Badge status={code} text={val} />;
      },
      filters: [
        {
          text: "已启用",
          value: "1"
        },
        {
          text: "已停用",
          value: "0"
        }
      ],
      filterMultiple: false
    },
    {
      title: "操作",
      dataIndex: "setId",
      key: "setId",
      width: "150px",
      render: (txt, record) => (
        <React.Fragment>
          <a
            onClick={() => {
              this.isForbidden(record);
            }}
          >
            {record.statusDesc === "已启用" ? "停用" : "启用"}
          </a>
          <Divider type="vertical" />
          <a
            onClick={() => {
              this.showModalFn(record, "edit");
            }}
          >
            编辑
          </a>
          <Divider type="vertical" />
          <Popconfirm
            placement="top"
            title={"确认要删除？"}
            onConfirm={() => {
              this.delete(record);
            }}
            okText="确定"
            cancelText="取消"
          >
            <a role="button">删除</a>
          </Popconfirm>
        </React.Fragment>
      )
    }
  ];

  componentDidMount() {
    this.refresh();
  }

  componentWillUnmount() {
    this.closeModal();
  }

  // 初始化页面
  refresh = () => {
    this.props.dispatch({
      type: "pushRules/pushRuleConfQuery",
      payload: {
        ruleName: null,
        pageIndex: 1,
        pageSize: 10,
        ruleDesc: null,
        ruleType: null,
        expDate: null,
        status: null,
        order: null // "asc"升序  desc:降序
      }
    });
  };

  // 禁止，启用状态
  isForbidden = (record = {}) => {
    const { id, statusDesc } = record;
    this.props.dispatch({
      type: "pushRules/pushRuleStatusMod",
      payload: {
        id,
        status: statusDesc === "已启用" ? "0" : "1"
      }
    });
  };

  delete = (record = {}) => {
    const id = String(record.id);
    this.props.dispatch({
      type: "pushRules/pushRuleConfDel",
      payload: { id }
    });
  };

  showModalFn(record, type) {
    this.setState({
      currentData: record,
      modalType: type
    });
    this.props.dispatch({ type: "pushRules/trigger/showModal", payload: true });
  }

  closeModal() {
    this.props.dispatch({
      type: "pushRules/trigger/showModal",
      payload: false
    });
  }

  // 表格变化(涵盖分页器变化)
  handleTableChange = (pagination = {}, filters = {}, sorter = {}) => {
    let order = null; // 有效期升降序
    let status = null; // 状态筛选
    const pageIndex = pagination.current; // 分页器页码变化
    const { pageSize } = pagination; // 分页器每页显示页数变化
    if (sorter.order) {
      if (sorter.order === "descend") {
        order = "desc";
      } else {
        order = "asc";
      }
    }
    if (filters.statusDesc) {
      if (filters.statusDesc.indexOf("1") > -1) {
        status = "1";
      } else if (filters.statusDesc.indexOf("0") > -1) {
        status = "0";
      }
    }
    this.props.dispatch({
      type: "pushRules/pushRuleConfQuery",
      payload: { order, status, pageIndex, pageSize }
    });
  };

  render() {
    const { pushRules = {}, dispatch } = this.props;
    const { list, totalCount, filter = {}, totalPage, showModal } = pushRules;
    const { currentData, modalType } = this.state;
    return (
      <div>
        {showModal ? (
          <PushRulesAdd
            dispatch={dispatch}
            showModal={showModal}
            dataSource={currentData}
            modalType={modalType}
            closeModal={this.closeModal.bind(this)}
          />
        ) : (
          <div className={styles.root}>
            <div className={styles.setDiv}>
              <span className={styles.title}>推送规则</span>
              <div className={styles.set}>
                <Button
                  type="primary"
                  onClick={() => {
                    this.showModalFn({}, "add");
                  }}
                >
                  新增规则
                </Button>
                <Search
                  placeholder="搜索"
                  onSearch={value => {
                    this.props.dispatch({
                      type: "pushRules/pushRuleConfQuery",
                      payload: {
                        ruleName: value === "" ? null : value,
                        pageIndex: 1
                      }
                    });
                  }}
                  className={styles.search}
                />
              </div>
            </div>
            <Table
              columns={this.columns}
              dataSource={list}
              rowKey={(item = {}) => item.ruleId}
              // size="middle"
              onChange={this.handleTableChange}
              pagination={{
                total: totalCount,
                pageSize: filter.pageSize,
                current: filter.pageIndex,
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: total =>
                  `共 ${total} 条记录 第 ${filter.pageIndex}/ ${totalPage}页`
              }}
            />
          </div>
        )}
      </div>
    );
  }
}

export default connect(stores => ({
  pushRules: stores.pushRules
}))(PushRules);
